package com.example.View;

import com.example.AlertHelper;
import com.example.PO.Order;
import com.example.Service.OrderService;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import java.util.List;
import java.util.stream.Collectors;

public class OrderView {
    private OrderService orderService = new OrderService();

    private TableView<Order> tableView;
    private ObservableList<Order> orderList;

    public OrderView() {
        tableView = new TableView<>();
        orderList = FXCollections.observableArrayList(orderService.getAllOrders());
        tableView.setItems(orderList);

        // 配置表格列
        TableColumn<Order, String> orderIdCol = new TableColumn<>("订单编号");
        orderIdCol.setCellValueFactory(new PropertyValueFactory<>("orderId"));

        TableColumn<Order, String> orderDateCol = new TableColumn<>("订单日期");
        orderDateCol.setCellValueFactory(new PropertyValueFactory<>("orderDate"));

        TableColumn<Order, String> totalAmountCol = new TableColumn<>("总金额");
        totalAmountCol.setCellValueFactory(new PropertyValueFactory<>("total_amount"));

        TableColumn<Order, String> deliveryDateCol = new TableColumn<>("交付日期");
        deliveryDateCol.setCellValueFactory(new PropertyValueFactory<>("deliveryDate"));

        TableColumn<Order, String> orderStatusCol = new TableColumn<>("订单状态");
        orderStatusCol.setCellValueFactory(new PropertyValueFactory<>("orderStatus"));

        TableColumn<Order, String> paymentStatusCol = new TableColumn<>("支付状态");
        paymentStatusCol.setCellValueFactory(new PropertyValueFactory<>("paymentStatus"));

        TableColumn<Order, String> remarkCol = new TableColumn<>("备注");
        remarkCol.setCellValueFactory(new PropertyValueFactory<>("remark"));

        TableColumn<Order, String> customerCol = new TableColumn<>("客户");
        customerCol.setCellValueFactory(new PropertyValueFactory<>("customer"));

        tableView.getColumns().addAll(orderIdCol, orderDateCol, totalAmountCol,
                deliveryDateCol, orderStatusCol, paymentStatusCol, remarkCol, customerCol);

        // 按钮和搜索框
        Button addButton = new Button("添加订单");
        Button editButton = new Button("编辑订单");
        Button deleteButton = new Button("删除订单");
        Button refreshButton = new Button("刷新");

        addButton.setOnAction(e -> showAddOrderDialog());
        editButton.setOnAction(e -> showEditOrderDialog());
        deleteButton.setOnAction(e -> deleteSelectedOrder());
        refreshButton.setOnAction(e -> refreshTable());

        HBox buttonBox = new HBox(10);
        buttonBox.getChildren().addAll(addButton, editButton, deleteButton, refreshButton);

        TextField searchField = new TextField();
        searchField.setPromptText("搜索订单");
        searchField.textProperty().addListener((obs, oldVal, newVal) -> filterTable(newVal));

        VBox view = new VBox(20);
        view.getChildren().addAll(searchField, buttonBox, tableView);
    }

    public VBox getView() {
        return (VBox) tableView.getParent();
    }

    private void showAddOrderDialog() {
        Dialog<Order> dialog = new Dialog<>();
        dialog.setTitle("添加订单");
        dialog.setHeaderText("填写订单详细信息");

        ButtonType addButtonType = new ButtonType("添加", ButtonBar.ButtonData.OK_DONE);
        dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);

        TextField orderDateField = new TextField();
        orderDateField.setPromptText("YYYY-MM-DD");
        TextField totalAmountField = new TextField();
        TextField deliveryDateField = new TextField();
        ComboBox<String> orderStatusCombo = new ComboBox<>(FXCollections.observableArrayList(
                "已下单", "处理中", "已发货", "已完成", "已取消"));
        ComboBox<String> paymentStatusCombo = new ComboBox<>(FXCollections.observableArrayList(
                "未支付", "已支付", "部分支付"));
        TextField remarkField = new TextField();
        ComboBox<String> customerCombo = new ComboBox<>();
        customerCombo.getItems().addAll(orderService.getAllOrders().stream()
                .map(Order::getOrderId).collect(Collectors.toList()));

        grid.addRow(0, new Label("订单日期:"), orderDateField);
        grid.addRow(1, new Label("总金额:"), totalAmountField);
        grid.addRow(2, new Label("交付日期:"), deliveryDateField);
        grid.addRow(3, new Label("订单状态:"), orderStatusCombo);
        grid.addRow(4, new Label("支付状态:"), paymentStatusCombo);
        grid.addRow(5, new Label("备注:"), remarkField);
        grid.addRow(6, new Label("客户:"), customerCombo);

        dialog.getDialogPane().setContent(grid);

        dialog.setResultConverter(buttonType -> {
            if (buttonType == addButtonType) {
                return new Order(
                        null, // ID由服务生成
                        orderDateField.getText(),
                        totalAmountField.getText(),
                        deliveryDateField.getText(),
                        orderStatusCombo.getValue(),
                        paymentStatusCombo.getValue(),
                        remarkField.getText(),
                        customerCombo.getValue()
                );
            }
            return null;
        });

        dialog.showAndWait().ifPresent(order -> {
            orderService.addOrder(order);
            orderList.add(order);
        });
    }

    private void showEditOrderDialog() {
        Order selected = tableView.getSelectionModel().getSelectedItem();
        if (selected != null) {
            Dialog<Order> dialog = new Dialog<>();
            dialog.setTitle("编辑订单");
            dialog.setHeaderText("修改订单信息");

            ButtonType saveButtonType = new ButtonType("保存", ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(saveButtonType, ButtonType.CANCEL);

            GridPane grid = new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);

            TextField orderDateField = new TextField(selected.getOrderDate());
            TextField totalAmountField = new TextField(selected.getTotal_amount());
            TextField deliveryDateField = new TextField(selected.getDeliveryDate());
            ComboBox<String> orderStatusCombo = new ComboBox<>(FXCollections.observableArrayList(
                    "已下单", "处理中", "已发货", "已完成", "已取消"));
            orderStatusCombo.setValue(selected.getOrderStatus());
            ComboBox<String> paymentStatusCombo = new ComboBox<>(FXCollections.observableArrayList(
                    "未支付", "已支付", "部分支付"));
            paymentStatusCombo.setValue(selected.getPaymentStatus());
            TextField remarkField = new TextField(selected.getRemark());
            ComboBox<String> customerCombo = new ComboBox<>(FXCollections.observableArrayList(
                    orderService.getAllOrders().stream().map(Order::getOrderId).collect(Collectors.toList())));
            customerCombo.setValue(selected.getCustomer());

            grid.addRow(0, new Label("订单日期:"), orderDateField);
            grid.addRow(1, new Label("总金额:"), totalAmountField);
            grid.addRow(2, new Label("交付日期:"), deliveryDateField);
            grid.addRow(3, new Label("订单状态:"), orderStatusCombo);
            grid.addRow(4, new Label("支付状态:"), paymentStatusCombo);
            grid.addRow(5, new Label("备注:"), remarkField);
            grid.addRow(6, new Label("客户:"), customerCombo);

            dialog.getDialogPane().setContent(grid);

            dialog.setResultConverter(buttonType -> {
                if (buttonType == saveButtonType) {
                    selected.setOrderDate(orderDateField.getText());
                    selected.setTotal_amount(totalAmountField.getText());
                    selected.setDeliveryDate(deliveryDateField.getText());
                    selected.setOrderStatus(orderStatusCombo.getValue());
                    selected.setPaymentStatus(paymentStatusCombo.getValue());
                    selected.setRemark(remarkField.getText());
                    selected.setCustomer(customerCombo.getValue());
                    return selected;
                }
                return null;
            });

            dialog.showAndWait().ifPresent(order -> {
                orderService.updateOrder(order);
                refreshTable();
            });
        }
    }

    private void deleteSelectedOrder() {
        Order selected = tableView.getSelectionModel().getSelectedItem();
        if (selected != null && AlertHelper.showConfirmationDialog("确认删除", "确定删除该订单？")) {
            orderService.deleteOrder(selected.getOrderId());
            orderList.remove(selected);
        }
    }

    private void refreshTable() {
        orderList.setAll(orderService.getAllOrders());
    }

    private void filterTable(String keyword) {
        if (keyword == null || keyword.isEmpty()) {
            refreshTable();
        } else {
            List<Order> filtered = orderService.getAllOrders().stream()
                    .filter(order ->
                            order.getOrderId().contains(keyword) ||
                                    order.getCustomer().contains(keyword) ||
                                    order.getOrderStatus().contains(keyword) ||
                                    order.getPaymentStatus().contains(keyword))
                    .collect(Collectors.toList());
            orderList.setAll(filtered);
        }
    }
}